package com.lms.web.borrowRecordManagement;

import com.lms.mapper.BorrowRecordDAO;
import com.lms.pojo.BorrowRecord;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@WebServlet(
        name = "ModifyBorrowRecordServlet",
        value = "/modifyBorrowRecord"
)
public class ModifyBorrowRecordServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int recordID = Integer.parseInt(req.getParameter("recordID"));
        int userId = Integer.parseInt(req.getParameter("userId"));
        int bookId = Integer.parseInt(req.getParameter("bookId"));
        String borrowDate = req.getParameter("borrowDate");
        String returnDate = req.getParameter("returnDate");
        String actualReturnDate = req.getParameter("actualReturnDate");
        boolean flag = false;
        if (recordID > 0) {
            BorrowRecordDAO dao = new BorrowRecordDAO();
            BorrowRecord borrowRecord = null;
            try {
                borrowRecord = new BorrowRecord(recordID, userId, bookId, stringToDate(borrowDate), stringToDate(returnDate), stringToDate(actualReturnDate));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            flag = dao.update(borrowRecord);
        }

        if (flag)//删除成功
        {
            // 重定向到借阅记录列表页面
            resp.sendRedirect("borrowRecord.jsp");
        } else {//删除失败
            req.setAttribute("error", "删除借阅失败");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    Date stringToDate(String str) throws ParseException {
        return new SimpleDateFormat("yyyy-MM-dd").parse(str);
    }
}
